package com.ruoyi.core.task.factory;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.domain.ClientProductUser;
import com.ruoyi.core.mapper.ClientProductUserMapper;
import com.ruoyi.core.task.CookieRefreshTPeriodicTriggerJob;
import com.ruoyi.core.task.JsPluginRefreshJob;
import com.ruoyi.core.task.JungleScoutCookieRefreshJob;
import com.ruoyi.core.task.MerchantWordCookieRefreshOnOffUpdateJob;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class DefaultPeriodicTriggerTaskFactory implements InitializingBean, PeriodicTriggerTaskFactory {
    private final Logger logger = LoggerFactory.getLogger(DefaultPeriodicTriggerTaskFactory.class);

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ClientProductUserMapper clientProductUserMapper;


    private final Map<String, CookieRefreshTPeriodicTriggerJob> jobMap = new HashMap<>();

    @Override
    public TriggerTaskBean getTriggerTask(String taskId, Integer period) {
        TriggerTaskBean triggerTaskBean = new TriggerTaskBean();

        triggerTaskBean.setTaskId(taskId);

        Runnable runnable = () -> {
            // 业务逻辑
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.info("{}:cookie refresh task perform  time {} ", taskId, simpleDateFormat.format(new Date()));
            String merchantWordProductId = sysConfigService.selectConfigByKey(taskId);

            if (!StringUtils.hasText(merchantWordProductId)) {
                logger.warn("{}:对应产品id不存在！", taskId);
                return;
            }

            Long productId = Long.parseLong(merchantWordProductId);
            List<ClientProductUser> clientProductUsers = clientProductUserMapper.findByProductId(productId);
            jobMap.get(taskId).start(clientProductUsers);

        };
        triggerTaskBean.setTriggerTask(new TriggerTask(runnable, getTrigger(period)));


        return triggerTaskBean;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MerchantWordCookieRefreshOnOffUpdateJob wordCookieRefreshOnOffUpdateJob = SpringUtils.getBean(MerchantWordCookieRefreshOnOffUpdateJob.class);
        jobMap.put("MERCHANT_WORD_PRODUCT_ID", wordCookieRefreshOnOffUpdateJob);

        JungleScoutCookieRefreshJob jungleScoutCookieRefreshJob = SpringUtils.getBean(JungleScoutCookieRefreshJob.class);

        jobMap.put("JUNGLE_SCOUT_PRODUCT_ID", jungleScoutCookieRefreshJob);

        JsPluginRefreshJob jsPluginRefreshJob = SpringUtils.getBean(JsPluginRefreshJob.class);

        jobMap.put("JS_PLUGIN_PRODUCT_ID", jsPluginRefreshJob);
    }

    private PeriodicTrigger getTrigger(Integer period) {
        // 触发器

        if (period == null) {
            logger.error("cookie refresh time interval must not be null ");
        }
        PeriodicTrigger trigger = new PeriodicTrigger(period, TimeUnit.MINUTES);
        trigger.setFixedRate(true);
        return trigger;
    }
}
